package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.SpeechManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;


public class SearchContactByName extends Activity {

	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.SearchContactByName.SHOW";
	private static final String TAG = SearchContactByName.class.getSimpleName();
	// Request code for the contact picker activity

	private SpeechManager speechManager;

	// Common to all features
	View view; 
	private Context context;
	private Vibrator vibrator;
	private KeyboardResultReceiver br;
	private IntentFilter receiverFilter;
		

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		context = getApplicationContext();
		speechManager = SpeechManager.getInstance(context);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

		receiverFilter=new IntentFilter("SearchContactByName_BR");
		receiverFilter.addCategory(Intent.CATEGORY_DEFAULT);
		
		br = new KeyboardResultReceiver();
		registerReceiver(br, receiverFilter);
		
		Intent intentKeyboard = new Intent("it.intecs.pisa.smarcos.activities.Keyboards.SHOW");
		intentKeyboard.putExtra("keyboardType", "QWERTY_KEYBOARD");
		intentKeyboard.putExtra("whereReturn", "SearchContactByName_BR");
		intentKeyboard.putExtra("messageToSay", "@string/TTS_Contact_WriteName");
		intentKeyboard.addCategory(Intent.CATEGORY_DEFAULT);
		startActivity(intentKeyboard);	
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "OnPause");	
		unregisterReceiver(br);
	}


	private String RetrieveContact(String contactName) {

		String contactNumberStr = null;
		Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, "upper("+ContactsContract.Contacts.DISPLAY_NAME+") = upper('"+ contactName +"')", null, null);

		int totalContacts = 0;
		int contactsWithNumber = 0;
		while (cursor.moveToNext()) {
			totalContacts++;
		
			String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
			if (cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)>0) { 
				contactsWithNumber++;
				// You know it has a number so now query it like this
				Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
				while (phones.moveToNext()) { 
					contactNumberStr = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));			
				} 
			}		
		}
		Log.d(TAG, "Total contacts: " + totalContacts + " With phone number: " + contactsWithNumber);
		cursor.close();
		return contactNumberStr;
	}

	
	public class KeyboardResultReceiver extends BroadcastReceiver {

		private final String TAG = KeyboardResultReceiver.class.getSimpleName();

		String contactNumberStr;
		
		@Override
		public void onReceive(Context arg0, Intent intent) {
			
			contactNumberStr = "";
			String result = intent.getStringExtra("Result");
			Log.d(TAG, "onReceive - " + result);

			Intent returnIntent;
			returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
			returnIntent.addCategory(Intent.CATEGORY_DEFAULT);	
			//sentResult = true;

			if (result.equals("NORESULT")) { 				
				returnIntent.putExtra("Result", "NORESULT");
			}else {
				Log.d(TAG, "Search inside contacts array " + result);	
				contactNumberStr = RetrieveContact(result); 
				Log.d(TAG, "Search inside contacts array " + contactNumberStr);	
				if (contactNumberStr == null || contactNumberStr.length() == 0){ 
					speechManager.say(getString(R.string.TTS_Contact_NoName), true, false);
					returnIntent.putExtra("Result", "NORESULT");
				}else {
					speechManager.say(getString(R.string.TTS_Contact_Found), true, false);
					returnIntent.putExtra("Result", contactNumberStr);
				}
			}

			sendBroadcast(returnIntent);	
			vibrator.vibrate(300);
			finish();
		}		
	}
}
